import books4africa.Donor
import books4africa.SecRole
import books4africa.SecUser
import books4africa.SecUserSecRole

class BootStrap {
	def springSecurityService

    def init = { servletContext ->
		
	//	def userRole = SecRole.findByAuthority('ROLE_USER') ?: new SecRole(authority: 'ROLE_USER').save(failOnError: true)
	//	def adminRole = SecRole.findByAuthority('ROLE_ADMIN') ?: new SecRole(authority: 'ROLE_ADMIN').save(failOnError: true)
		
//		
//		def adminUser = SecUser.findByUsername('admin') ?: new SecUser(
//			username: 'admin@maine.edu',
//			password: 'password',
//			enabled: true).save(failOnError: true)
//			
//		if(!adminUser.authorities.contains(adminRole)){
//			SecUserSecRole.create adminUser, adminRole
//		}
		def sampleUsers = [
			'Donor1@maine.edu',
			'Donor2@maine.edu'	
		]
				
		def userRole = getOrCreateRole("ROLE_USER")
		def adminRole = getOrCreateRole("ROLE_ADMIN")
		
		def users = Donor.list() ?: []
		if(!users){
			//start with an admin user
			def adminUser = new Donor(
				username: "admin@maine.edu",
				password: "s3cur3",//springSecurityService.encodePassword("s3cur3"),
				enabled: true).save()
			SecUserSecRole.create adminUser, adminRole
			
			//Now the normal users
			sampleUsers.each { username ->
				def donor = new Donor(
					username: username,
					password: "password",//springSecurityService.encodePassword("password"),
					enabled: true)
                if(donor.validate()){
					println "Creating donor ${username}..."
					donor.save(flush: true)
					
					def rel = SecUserSecRole.create(donor, userRole)
					if (rel.hasErrors()) println "Failed to assign user role to ${donor.username}: ${rel.errors}"
					
					users << donor
				}else{
					println("\n\nError in account bootstrap for ${username}!\n\n\n")
					donor.errors.each {err ->
						println err
					}
			    }
		    }		
        }
    }
    def destroy = {
    }
	private getOrCreateRole(name) {
		def role = SecRole.findByAuthority(name)
		if(!role) role = new SecRole(authority: name).save()
		if(!role) println "Unable to save role ${name}"
		return role		
		
		
	}
    
}
